package com.infinitus.nginxInfo.config;

import java.util.Map.Entry;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfFileItem;
import com.baidu.disconf.client.common.annotations.DisconfUpdateService;

/**
 * 项目中所有url接口
 *
 */
@Component
@DisconfFile(filename = "url-config.properties")
@DisconfUpdateService(classes = {FetchUrlConfig.class})
public class FetchUrlConfig implements InitializingBean {

	
	@Value("${fetch.shuguo.url}")
	private static String shuguoUrl;
	
	@Value("${sugo.field.type.url}")
	private String filedTypeUrl;
	
	@Value("${sugo.field.type.map}")
	private String fieldTypeMap;
	
	
	public String getFiledTypeUrl(String topic) {
		return String.format(filedTypeUrl, topic) ;
	}


	@DisconfFileItem(name = "fetch.shuguo.url", associateField = "shuguoUrl")
	public static String getShuguoUrl() {
		return shuguoUrl;
	}

	@DisconfFileItem(name = "sugo.field.type.url", associateField = "filedTypeUrl")
	public String getFiledTypeUrl() {
		return filedTypeUrl;
	}
	
	@DisconfFileItem(name = "sugo.field.type.map", associateField = "fieldTypeMap")
	public String getFieldTypeMap() {
		return fieldTypeMap;
	}

	public void setFieldTypeMap(String fieldTypeMap) {
		try{
			initFieldTypeMap(fieldTypeMap);
			this.fieldTypeMap = fieldTypeMap;
		}catch(Exception e){
			try {
				initFieldTypeMap(this.fieldTypeMap);
			} catch (Exception e1) {
			}
			e.printStackTrace();
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		initFieldTypeMap(fieldTypeMap);
	}

	private void initFieldTypeMap(String fieldTypeMap)  throws Exception {
		JSONObject json = JSONObject.parseObject(fieldTypeMap);
		for(Entry<String, Object> entry : json.entrySet()){
			String updateKey = entry.getKey();
			String updateValue = (String) entry.getValue();
			String cacheValue = StaticCache.FILEDTYPE_MAP.get(updateKey);
			if(updateValue!=null &&(cacheValue==null || !cacheValue.equals(updateValue))){
				StaticCache.FILEDTYPE_MAP.put(updateKey, updateValue);
			}
		}
	}
	
}
